package com.ruoyi.service.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.service.project.entity.ProjectSettleDetailEntity;
import com.ruoyi.service.project.entity.ProjectSettleEntity;
import com.ruoyi.service.project.enums.SettleStatusEnum;
import com.ruoyi.service.project.enums.SettleTypeEnum;
import com.ruoyi.service.project.mapper.ProjectSettleDetailMapper;
import com.ruoyi.service.project.service.ProjectSettleDetailService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 项目结算单明细 服务实现类
 * </p>
 *
 * @author Zane
 * @since 2025-10-26
 */
@Service
public class ProjectSettleDetailServiceImpl extends
    ServiceImpl<ProjectSettleDetailMapper, ProjectSettleDetailEntity>
    implements ProjectSettleDetailService {

  @Override
  public List<ProjectSettleDetailEntity> listByProjectIds(List<String> projectIds) {
    return list(queryWrapper().in(ProjectSettleDetailEntity::getProjectId, projectIds));
  }

  @Override
  public Map<String, List<ProjectSettleDetailEntity>> groupMapByProjectIds(
      List<String> projectIds) {
    return Optional.ofNullable(listByProjectIds(projectIds)).orElseGet(ArrayList::new)
        .stream().collect(Collectors.groupingBy(ProjectSettleDetailEntity::getProjectId));
  }

  @Override
  public BigDecimal sumSettling(Long userId) {
    //子查询,获得结算中的项目
    final String subSql = new LambdaQueryWrapper<ProjectSettleEntity>()
        .select(ProjectSettleEntity::getProjectId)
        .eq(ProjectSettleEntity::getSettleStatus, SettleStatusEnum.settling)
        .getSqlSelect();
    return Optional.ofNullable(list(queryWrapper()
            .eq(ProjectSettleDetailEntity::getTargetId, userId)
            .eq(ProjectSettleDetailEntity::getSettleType, SettleTypeEnum.SALARY.getCode())
            .in(ProjectSettleDetailEntity::getProjectId, subSql))
        )
        .orElseGet(ArrayList::new)
        .stream().map(ProjectSettleDetailEntity::getSettleAmount).reduce(BigDecimal::add)
        .orElse(BigDecimal.ZERO);
  }

  @Override
  public List<ProjectSettleDetailEntity> listByProjectId(String projectId) {
    return list(queryWrapper().eq(ProjectSettleDetailEntity::getProjectId, projectId));
  }

  private LambdaQueryWrapper<ProjectSettleDetailEntity> queryWrapper() {
    return new LambdaQueryWrapper<>();
  }

}
